package com.gtgj.widget;

import com.gtgj.widget.calender.GTLunarCalendarV2;
import com.gtgj.widget.model.DateInfo;
import com.gtgj.widget.slice.WebAbilitySlice;
import com.gtgj.widget.util.DataUtils;
import com.gtgj.widget.util.DateUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentProvider;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.event.intentagent.IntentAgent;
import ohos.event.intentagent.IntentAgentConstant;
import ohos.event.intentagent.IntentAgentHelper;
import ohos.event.intentagent.IntentAgentInfo;
import ohos.global.resource.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;
import java.util.*;

public class MainAbility extends Ability {
    public static final int DEFAULT_DIMENSION_2X2 = 2;
    public static final int DEFAULT_DIMENSION_2X4 = 3;
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, MainAbility.class.getName());
    private int beforeDay = 14;
    private int afterDay = 15;
    private int maxDay = 15;
    int weekIds[] =new int[]{ResourceTable.Id_week,ResourceTable.Id_week2,ResourceTable.Id_week3,ResourceTable.Id_week4,ResourceTable.Id_week5,ResourceTable.Id_week6,ResourceTable.Id_week7};
    int solarIds[] =new int[]{ResourceTable.Id_solar_day,ResourceTable.Id_solar_day2,ResourceTable.Id_solar_day3,ResourceTable.Id_solar_day4,ResourceTable.Id_solar_day5,ResourceTable.Id_solar_day6,ResourceTable.Id_solar_day7};
    int lunarIds[] =new int[]{ResourceTable.Id_lunar_day,ResourceTable.Id_lunar_day2,ResourceTable.Id_lunar_day3,ResourceTable.Id_lunar_day4,ResourceTable.Id_lunar_day5,ResourceTable.Id_lunar_day6,ResourceTable.Id_lunar_day7};
    int month2Ids[]=new int[]{ResourceTable.Id_space_1,ResourceTable.Id_space_2,ResourceTable.Id_space_3,ResourceTable.Id_space_4,ResourceTable.Id_space_5,ResourceTable.Id_space_6};
    int monthTxtIds[]=new int[]{ResourceTable.Id_month1,ResourceTable.Id_month2,ResourceTable.Id_month3,ResourceTable.Id_month4,ResourceTable.Id_month5,ResourceTable.Id_month6};
    int dateIds[] = new int[]{ResourceTable.Id_dl1,ResourceTable.Id_dl2,ResourceTable.Id_dl3,ResourceTable.Id_dl4,ResourceTable.Id_dl5,ResourceTable.Id_dl6};

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(WebAbilitySlice.class.getName());
        beforeDay = DataUtils.readDate(getApplicationContext(), "beforeDay");
        afterDay = DataUtils.readDate(getApplicationContext(), "afterDay");
    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, 0);
        String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        int specificationId = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        boolean tempFlag = intent.getBooleanParam(AbilitySlice.PARAM_FORM_TEMPORARY_KEY, false);

        // 获取自定义数据
        IntentParams intentParams = intent.getParam(AbilitySlice.PARAM_FORM_CUSTOMIZE_KEY);

        HiLog.info(TAG, "onCreateForm: " + formId + " " + formName + " " + specificationId);
        DataUtils.insertForm(getApplicationContext(), formId, formName, specificationId);
        // 开发者需要根据卡片的名称以及外观规格获取对应的xml布局并构造卡片对象，此处ResourceTable.Layout_form_ability_layout_2_2仅为示例
        ProviderFormInfo formInfo = new ProviderFormInfo(specificationId == DEFAULT_DIMENSION_2X4 ? ResourceTable.Layout_form_date_layout_2_4 : ResourceTable.Layout_form_date_layout_2_2, this);
        if (specificationId == DEFAULT_DIMENSION_2X4) {
            build24Form(formInfo);
        } else {
            build22Form(formInfo);
        }
        return formInfo;
    }

    private void build22Form(ProviderFormInfo formInfo) {
        ComponentProvider componentProvider = formInfo.getComponentProvider();
        int beforeBuyDateCount = beforeDay;
        if (beforeBuyDateCount == -1) {
            beforeBuyDateCount = 14;
        }
        int afterBuyDateCount = afterDay;
        if (afterBuyDateCount == -1) {
            beforeBuyDateCount = 15;
        }
        int maxOrderTicketDays = maxDay;
        if (maxOrderTicketDays == -1) {
            maxOrderTicketDays = 30;
        }
        if (maxOrderTicketDays > 0) {
            maxOrderTicketDays--;
        }
        List<DateInfo> dateInfos = GTLunarCalendarV2.generateYueQiangDateInfos(maxOrderTicketDays, beforeBuyDateCount, afterBuyDateCount);
        int todayKaiShouPosition = GTLunarCalendarV2.getTodayKaiShouPosition(dateInfos);
        if (todayKaiShouPosition >= 0 && todayKaiShouPosition < dateInfos.size()) {
            Date date = new Date(dateInfos.get(todayKaiShouPosition).getDate());
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            componentProvider.setText(ResourceTable.Id_subTitle, GTLunarCalendarV2.GetDateNL(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH)) + " " +
                    GTLunarCalendarV2.getMixHoliday(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH)));
            componentProvider.setText(ResourceTable.Id_month, String.format("%02d", cal.get(Calendar.MONTH) + 1));
            componentProvider.setText(ResourceTable.Id_day, String.format("%02d", cal.get(Calendar.DAY_OF_MONTH)));
        }
        componentProvider.setIntentAgent(ResourceTable.Id_widget, getDateIntentAgent());
        formInfo.mergeActions(componentProvider);
    }

    private void build24Form(ProviderFormInfo formInfo) {
        ComponentProvider componentProvider = formInfo.getComponentProvider();
        int beforeBuyDateCount = beforeDay;
        if (beforeBuyDateCount == -1) {
            beforeBuyDateCount = 14;
        }
        int afterBuyDateCount = afterDay;
        if (afterBuyDateCount == -1) {
            beforeBuyDateCount = 15;
        }
        int maxOrderTicketDays = maxDay;
        if (maxOrderTicketDays == -1) {
            maxOrderTicketDays = 30;
        }
        if (maxOrderTicketDays > 0) {
            maxOrderTicketDays--;
        }
        List<DateInfo> dateInfos = GTLunarCalendarV2.generateYueQiangDateInfos(maxOrderTicketDays, beforeBuyDateCount, afterBuyDateCount);
        int todayKaiShouPosition = GTLunarCalendarV2.getTodayKaiShouPosition(dateInfos);
        HiLog.info(TAG, "build form 24: today " + todayKaiShouPosition + " infos is " + Arrays.toString(dateInfos.toArray()));
        if (todayKaiShouPosition >= 0 && todayKaiShouPosition < dateInfos.size()) {
            Date date = new Date(dateInfos.get(todayKaiShouPosition).getDate());
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            componentProvider.setText(ResourceTable.Id_sell_date, DateUtils.MMddC().format(date));
            List<DateInfo> dates = dateInfos.subList(todayKaiShouPosition, Math.min(todayKaiShouPosition + 6, dateInfos.size()));
            componentProvider.setText(ResourceTable.Id_month, dates.get(0).getTitleDate());
            for (int i = 0; i < dates.size() ; i++) {
                if (i > 0 && !dates.get(i).getTitleDate().equals(dates.get(i-1).getTitleDate())) {
                    setMonth(i, dates.get(i), componentProvider);
                }
                setTime(i, dates.get(i), componentProvider);
            }
        }
        componentProvider.setIntentAgent(ResourceTable.Id_widget, getDateIntentAgent());
        formInfo.mergeActions(componentProvider);
    }

    private void setMonth(int index, DateInfo dateInfo, ComponentProvider componentProvider) {
        componentProvider.setVisibility(month2Ids[index-1], Component.VISIBLE);
        componentProvider.setText(monthTxtIds[index-1], dateInfo.getTitleDate());
    }

    private void setTime(int index, DateInfo dateInfo, ComponentProvider componentProvider) {
        componentProvider.setText(weekIds[index], dateInfo.getWeekText());
        componentProvider.setText(solarIds[index], dateInfo.getSolarText());
        componentProvider.setText(lunarIds[index],dateInfo.getLunarText());
        if (dateInfo.isTodayKaiShou()) {
            componentProvider.setTextColor(solarIds[index], new Color(Color.getIntColor("#1188ff")));
            componentProvider.setTextColor(lunarIds[index], new Color(Color.getIntColor("#1188ff")));
            componentProvider.setText(lunarIds[index], "今日开售");
            Optional<PixelMap> pixelMap = getPixelMap(this, ResourceTable.Graphic_bg_date);
            if (pixelMap.isPresent()) {
                componentProvider.setBackgroundPixelMap(dateIds[index], pixelMap.get());
            }
        }
    }

    private IntentAgent getDateIntentAgent() {
        // 设置点击的跳转页面
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(MainAbility.class.getName())
                .build();
        intent.setParam("url", "https://h5.133.cn/gtgjwap/h5/ticketAgent/home?ptid=vivoscreen");
        intent.setOperation(operation);
        List<Intent> intentList = new ArrayList<>();
        intentList.add(intent);
        // 对于不同的响应事件，第一个参数requestCode需要不同，此处用电影id设为requestCode
        IntentAgentInfo paramsInfo = new IntentAgentInfo(0,
                IntentAgentConstant.OperationType.START_ABILITY,
                IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG, intentList, null);
        IntentAgent intentAgent = IntentAgentHelper.getIntentAgent(this, paramsInfo);
        return intentAgent;
    }

    private IntentAgent getTripIntentAgent() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(MainAbility.class.getName())
                .build();
        intent.setParam("url", "");
        intent.setOperation(operation);
        List<Intent> intentList = new ArrayList<>();
        intentList.add(intent);
        IntentAgentInfo paramsInfo = new IntentAgentInfo(0,
                IntentAgentConstant.OperationType.START_ABILITY,
                IntentAgentConstant.Flags.UPDATE_PRESENT_FLAG, intentList, null);
        IntentAgent intentAgent = IntentAgentHelper.getIntentAgent(this, paramsInfo);
        return intentAgent;
    }

    @Override
    protected void onUpdateForm(long formId) {
        super.onUpdateForm(formId);
        //todo update
    }

    @Override
    protected void onDeleteForm(long formId) {
        super.onDeleteForm(formId);
        DataUtils.deleteForm(getApplicationContext(), formId);
    }


    private void updateAllFrom() {
        // 获取卡片集合
        String trip = DataUtils.getTrip(getApplicationContext());
//        Map<String, ?> forms = preferences.getAll();
//        for (String formId : forms.keySet()) {
//            try {
//                ZSONObject zsonObject = CommonUtils.getJsBindData(top, bottom, topMovie, bottomMovie);
//            } catch (FormException e) {
//            }
//        }
    }

    /**
     * get the pixel map
     *
     * @param context the context
     * @param id      the id
     * @return the pixel map
     */
    public static Optional<PixelMap> getPixelMap(Context context, int id) {
        String path = null;
        try {
            path = context.getResourceManager().getMediaPath(id);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        if (TextTool.isNullOrEmpty(path)) {
            return Optional.empty();
        }
        RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/png";
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        try {
            Resource asset = assetManager.openRawFile();
            ImageSource source = ImageSource.create(asset, options);
            return Optional.ofNullable(source.createPixelmap(decodingOptions));
        } catch (IOException e) {
        }
        return Optional.empty();
    }
}
